<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图  -->
    <el-card>
      <!-- 提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="step - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addForm" ref="addForm" :rules="rules" label-position="top">
        <!-- tabs内容 -->
        <el-tabs tab-position="left" v-model="step" :before-leave="beforeLeaveHandel" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" placeholder="请输入商品名称" size="normal" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price" placeholder="请输入商品价格" size="normal" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight" placeholder="请输入商品重量" size="normal" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number" placeholder="请输入商品数量" size="normal" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cascaderProp" clearable @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(itemVal, index) in item.attr_vals" :label="itemVal" :key="index">{{ itemVal }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals" placeholder="请输入商品属性" clearable></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload class="" :action="upload" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handelSuccess" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce" />
            <el-button type="primary" class="submit" size="default" @click="add('addForm')">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="dialogPreveiwVisible" width="50%">
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash' //导入lodash
export default {
  data() {
    return {
      step: 0,
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '', //商品分类列表
        pics: [], //商品图片数组
        goods_introduce: '', //商品详情描叙
        attrs: []
      },
      rules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur,change' }]
      },
      selectedCateId: [], //选择分类id
      cateList: [], //商品分类列表
      cascaderProp: {
        //指定级联对象配置选项
        // expandTrigger: 'hover' ,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      manyTableData: [], //动态参数列表
      onlyTableData: [], //静态属性参数列表
      upload: process.env.VUE_APP_BASEURL + '/upload', //图片上传路径
      headerObj: {
        //图片上传组件请求头
        Authorization: sessionStorage.token
      },
      previewPath: '', //预览图片路径
      dialogPreveiwVisible: false
    }
  },
  mounted() {
    this.getCateList()
    console.log('id', this.$route.query.id)
    if (this.$route.query.id) {
      //如果是编辑
      this.getGoodsDetail()
    }
  },
  methods: {
    getGoodsDetail() {
      //获取商品详情
      this.$http
        .get(`/goods/${this.$route.query.id}`)
        .then(res => {
          res = res.data
          // console.log(res)
          if (res.meta.status == 200) {
            this.addForm = res.data
            this.$nextTick(() => {
              this.addForm.goods_cat = this.addForm.goods_cat.split(',')
            })
            console.log('addForm', this.addForm)
          } else {
            this.$message({ type: 'error', message: res.meta.msg })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getCateList() {
      //获取所有参数列表
      this.$http
        .get('/categories')
        .then(res => {
          res = res.data
          if (res.meta.status != 200) {
            //报错就直接返回
            this.$message({ type: 'error', message: res.meta.msg })
            return
          }
          this.cateList = res.data
          // console.log('cateList',this.cateList)
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleChange() {
      //级联点击事件
      console.log('selectedCateId', this.addForm.goods_cat)
      if (this.addForm.goods_cat.length != 3) {
        //没有选择3级分类
        this.addForm.goods_cat = []
        return
      }
    },
    beforeLeaveHandel(activeName, oldActiveName) {
      //tabs切换标签之前的钩子
      // console.log('oldActiveName:'+oldActiveName+',activeName:'+activeName)
      if ((oldActiveName == 0) & (this.addForm.goods_cat.length != 3)) {
        this.$message({ type: 'error', message: '请先选择商品分类' })
        return false
      }
    },
    tabClicked() {
      //tabs点击事件
      // console.log('step',this.step)
      if (this.step == 1) {
        //访问动态参数面板
        this.getParamList('many')
      } else if (this.step == 2) {
        //访问静态属性
        this.getParamList('only')
      }
    },
    getParamList(activeName) {
      //获取所有分类列表
      const data = {
        sel: activeName
      }
      this.$http
        .get(`/categories/${this.cateId}/attributes`, { params: data })
        .then(res => {
          res = res.data
          if (res.meta.status != 200) {
            //报错就直接返回
            this.$message({ type: 'error', message: res.meta.msg })
            return
          }
          console.log('data', res.data)
          if (activeName == 'many') {
            //处理attr_vals
            res.data.forEach(item => {
              // 处理attr_vals为数组
              item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
            })
            this.manyTableData = res.data
          } else {
            this.onlyTableData = res.data
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleRemove(file, fileList) {
      //图片删除
      console.log(file, fileList)
      const tmp_path = file.response.data.tmp_path //图片临时路径
      const i = this.addForm.pics.findIndex(x => x.pic === tmp_path) //找到图片索引
      this.addForm.pics.splice(i, 1) //移除图片
      console.log('pics', this.addForm.pics)
    },
    handlePreview(file) {
      //图片预览事件
      console.log(file)
      this.previewPath = file.response.data.url //图片完整路径
      this.dialogPreveiwVisible = true
    },
    handelSuccess(response) {
      //图片上传成功事件
      // console.log(response)
      const picObj = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picObj)
      console.log('pics', this.addForm.pics)
    },
    add(formName) {
      //添加商品
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.addForm.goods_name) {
            this.$message({ type: 'error', message: '请填写商品名称' })
            return
          }
          if (!this.addForm.goods_price) {
            this.$message({ type: 'error', message: '请输入商品价格' })
            return
          }
          if (!this.addForm.goods_weight) {
            this.$message({ type: 'error', message: '请填写商品重量' })
            return
          }
          if (!this.addForm.goods_number) {
            this.$message({ type: 'error', message: '请填写商品数量' })
            return
          }
          // lodash
          const form = _.cloneDeep(this.addForm)
          form.attrs = [] //清空一下，防止重复
          form.goods_cat = form.goods_cat.join(',')
          //处理动态参数
          this.manyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(',')
            }
            form.attrs.push(newInfo)
          })
          //处理静态属性
          this.onlyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            form.attrs.push(newInfo)
          })
          // form.attrs=this.addForm.attrs
          console.log('form', form)
          this.$http.post(`goods`, form).then(res => {
            res = res.data
            if (res.meta.status != 201) {
              //报错就直接返回
              this.$message({ type: 'error', message: res.meta.msg })
              return
            }
            console.log('data', res.data)
            this.$message({ type: 'sucess', message: res.meta.msg })
            this.$router.push('/goods')
          })
        } else {
          this.$message({ type: 'error', message: '请填写商品信息' })
          return
        }
      })
    }
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat.length == 3 ? this.addForm.goods_cat[this.addForm.goods_cat.length - 1] : ''
    }
  }
}
</script>

<style scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.quill-editor {
  min-height: 300px;
}
.quill-editor /deep/ .ql-container.ql-snow {
  min-height: 300px;
}
.el-form /deep/ .submit {
  margin-top: 20px;
}
</style>
